# -*- coding: utf-8 -*-
import base64
import random
import subprocess
import time
import logging
import argparse
from datetime import datetime, timedelta

import cv2
import numpy as np
from appium import webdriver
# from appium.options.android import UiAutomator2Options
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
logger = logging

APP = "WB"

app_package_map = {
    "WB": ("com.sina.weibo", ".VisitorMainTabActivity")
}


class WBAppiumOperate:
    def __init__(self, **kwargs):
        self.screen_width = None
        self.screen_height = None
        self.like_prob = kwargs.get("like_prob", 0.2) / 100
        self.search_prob = kwargs.get("searchProb", 0.2) / 100
        self.key_word = kwargs.get("keyWord", "美食\n旅行\n健身").replace("\\n", "\n")
        # self.collect_prob = kwargs.get("comment_prob", 0.1) / 100
        self.follow_prob = kwargs.get("follow_prob", 0.05) / 100
        self.seconds = kwargs.get("seconds", 60 * 10)  # 默认运行10分钟
        self.deviceName = kwargs.get("deviceName")
        self.appium_url = kwargs.get("appium_url")
        self.platformVersion = kwargs.get("platformVersion")
        self.systemPort = kwargs.get("systemPort")
        self.adbPort = kwargs.get("adbPort")

        self.driver = None
        self.max_retries = 3
        self.failure_count = 0
        self.view_count = 0
        self.like_count = 0
        self.comment_count = 0
        self.follow_count = 0

    def run(self):
        while self.max_retries > 0:
            try:
                if self.driver:
                    self.driver.quit()
                # 清理clear io.appium.uiautomator2.server storage
                self.connection()
                logger.info(f"设备 {self.deviceName} 连接成功")
                time.sleep(3)

                logger.info("开始执行微博养号任务...")
                self.script()
                break
            except Exception as e:
                logger.error(f"发生异常: {e}")
                self.failure_count += 1
                self.max_retries -= 1
                if self.max_retries == 0:
                    self.normal_end()
                    raise Exception("任务失败")
        logger.info("任务结束")

    @staticmethod
    def execute_adb_command(adb_command):
        """
        执行单条 ADB 命令

        :param adb_command: 完整的 ADB 命令字符串
        :return: 命令执行结果（stdout）
        """
        try:
            logger.info(f"执行 ADB 命令: {adb_command}")
            result = subprocess.run(
                adb_command,
                shell=True,
                check=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
            logger.info(f"命令执行成功: {adb_command}")
            return result.stdout.decode('utf-8')
        except subprocess.CalledProcessError as e:
            logger.error(f"命令执行失败: {adb_command}")
            logger.error(f"错误信息: {e.stderr.decode('utf-8')}")

    def initialize_device_settings(self):
        """
        执行设备初始化所需的 ADB 命令
        """
        logger.info("开始初始化设备设置")

        commands = [
            f"adb -s {self.deviceName} -P {self.adbPort} shell settings put global adb_keep_usb_enabled 1",
            f"adb -s {self.deviceName} -P {self.adbPort} shell settings put global miui_optimization 0",
            f"adb -s {self.deviceName} -P {self.adbPort} shell settings put global tcp_keepalive 1",
            f"adb -s {self.deviceName} -P {self.adbPort} shell dumpsys battery unplug",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm enable io.appium.uiautomator2.server",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm enable io.appium.uiautomator2.server.test",
            f"adb -s {self.deviceName} -P {self.adbPort} shell settings put global background_process_limit 5",
            f"adb -s {self.deviceName} -P {self.adbPort} shell am set-standby-bucket io.appium.uiautomator2.server ACTIVE",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm trim-caches 500M",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm clear io.appium.uiautomator2.server",
            f"adb -s {self.deviceName} -P {self.adbPort} shell pm clear io.appium.uiautomator2.server.test",
            f"adb -s {self.deviceName} -P {self.adbPort} shell input keyevent KEYCODE_CLEAR"
        ]

        for cmd in commands:
            try:
                self.execute_adb_command(cmd)
            except Exception as e:
                logger.error(f"执行命令失败: {cmd}")
                logger.error(f"错误详情: {e}")

    def connection(self):
        self.initialize_device_settings()
        desired_caps = {
            "udid": "FMR0223A31045650",
            "udid": self.deviceName,
            "platformName": "Android",
            "platformVersion": self.platformVersion,
            "deviceName": self.deviceName,
            "automationName": "UiAutomator2",
            "appPackage": app_package_map[APP][0],
            "appActivity": app_package_map[APP][1],
            "noReset": True,
            "fullReset": False,
            "systemPort": int(self.systemPort),
            "adbPort": int(self.adbPort),
            "appWaitForLaunch": True,
            "noSign": True,
            "autoLaunch": True,
            "newCommandTimeout": 180,
            "skipLogcatCapture": True,
            "disableWindowAnimation": True,
            "disableAndroidWatchers": True,
            "adbExecTimeout": 30000,
            "uiautomator2ServerInstallTimeout": 60000,
            "skipDeviceInitialization": True,
        }

        self.driver = webdriver.Remote(self.appium_url, desired_caps)
        # self.driver = webdriver.Remote(self.appium_url, options=UiAutomator2Options().load_capabilities(desired_caps))
        self.screen_width, self.screen_height = self.get_window_size()

    def script(self):

        self._wait_splash_ad_done()
        start_time = datetime.now()

        logger.info("开始浏览微博推荐页")

        while (datetime.now() - start_time).seconds < self.seconds:
            is_search = False
            self.view_count += 1
            logger.info(f"正在浏览第 {self.view_count} 屏内容")

            # 随机搜索
            if random.random() < self.search_prob:
                keyword = self.key_word.split("\n")
                keyword.append("")
                search_word = random.choice(keyword)
                if search_word != "":
                    logger.info(f"正在搜索: {search_word}")

                    # 1. 点击“发现”按钮
                    discover_button = self.find_element_with_retry(
                        by=AppiumBy.XPATH,
                        value='//android.widget.FrameLayout[@content-desc="发现"]',
                        timeout=5
                    )
                    discover_button.click()
                    time.sleep(3)
                    self.swipe_to_next()
                    time.sleep(4)
                    self.swipe_to_next()

                    # 2. 在发现页点击“搜索”按钮

                    search_button = self.find_element_with_retry(
                        by=AppiumBy.XPATH,
                        value='//android.widget.ImageView[@resource-id="com.sina.weibo:id/iv_searchbar_bg_center"]',
                        timeout=5
                    )
                    logger.info(f"找到顶部搜索按钮")
                    search_button.click()
                    time.sleep(5)

                    # 3. 输入关键词
                    search_edit_text = self.find_element_with_retry(
                        by=AppiumBy.XPATH,
                        value='//android.widget.EditText[@resource-id="com.sina.weibo:id/et_input"]',
                        timeout=5
                    )

                    search_edit_text.send_keys(search_word)
                    time.sleep(5)

                    # 4. 点击软键盘上的“搜索”按钮
                    self.driver.press_keycode(66)  # 模拟按下“回车”键进行搜索
                    time.sleep(4)
                    self.swipe_to_next()
                    time.sleep(4)
                    self.swipe_to_next()

                    is_search = True
                    swipe_times = random.randint(2, 8)
                    self.view_count = 0
                    for i in range(swipe_times):
                        time.sleep(5)
                        self.swipe_to_next()
                        self.view_count += 1
                        logger.info(f"is_search={is_search}, 正在浏览第 {self.view_count} 屏（搜索页）")
                        default_value = 2
                        if self.view_count % default_value == 0:
                            self.try_click_card()

                    time.sleep(random.uniform(6, 10))

                    self.driver.press_keycode(4)
                    logger.info("不浏览发现页了，进行返回首页，触发返回第1次")
                    time.sleep(random.uniform(6, 10))

                    self.driver.press_keycode(4)
                    time.sleep(random.uniform(6, 10))
                    logger.info("不浏览发现页了，进行返回首页，触发返回第2次")

                    self.driver.press_keycode(4)
                    time.sleep(random.uniform(6, 10))
                    logger.info("不浏览发现页了，进行返回首页，触发返回第3次")

                    back_to_top_button = self.find_element_with_retry(
                        by=AppiumBy.XPATH,
                        value='//android.widget.FrameLayout[@content-desc="返回顶部"]',
                        timeout=5
                    )
                    # 点击“返回顶部”按钮
                    if back_to_top_button:
                        back_to_top_button.click()

                    home_button = self.find_element_with_retry(
                        by=AppiumBy.XPATH,
                        value='//android.widget.FrameLayout[@content-desc="首页"]',
                        timeout=5
                    )
                    if home_button:
                        # 点击“首页”按钮
                        home_button.click()

            # 随机滑动推荐页
            self.swipe_to_next()
            time.sleep(random.uniform(1.5, 3))
            self.swipe_to_next()
            time.sleep(random.uniform(1.5, 3))
            if random.random() < 0.75:
                self.swipe_to_next()
                time.sleep(random.uniform(1.5, 3))

            # 随机点击一个笔记或视频入口
            default_value = 4
            if not is_search and self.view_count % default_value == 0:  # 每隔几篇进入详情页
                self.try_click_card()
            time.sleep(random.uniform(2, 5))

        self.normal_end()

    def _wait_splash_ad_done(self, timeout=30):
        """
        不再点击跳过，而是等待开屏广告倒计时结束
        timeout：最长等待时间（秒）
        """
        logger.info("⏳ 检测到开屏广告，等待其自然结束 …")
        t0 = time.time()

        while time.time() - t0 < timeout:
            # 1. 倒计时数字（常见 id，可按实际包名/文案调整）
            countdown_digits = self.driver.find_elements(
                AppiumBy.XPATH,
                '//*[contains(@resource-id,"countdown") or contains(@resource-id,"skip") or contains(@text,"跳过")]'
            )

            # 2. 如果没有倒计时元素，说明广告结束
            if not countdown_digits:
                logger.info("✅ 广告倒计时结束，继续后续流程")
                return

            # 3. 广告仍在，sleep 1 秒后继续检测
            time.sleep(1)

        logger.info("⏰ 广告等待超时，强制继续后续流程")

    def is_note_detail_page(self):
        try:
            self.find_element_with_retry(by=AppiumBy.ANDROID_UIAUTOMATOR,
                                         value='new UiSelector().resourceId("com.sina.weibo:id/btn_comments_new")')
            self.find_element_with_retry(by=AppiumBy.ANDROID_UIAUTOMATOR,
                                         value='new UiSelector().resourceId("com.sina.weibo:id/btn_like")')
            return True
        except NoSuchElementException:
            return False

    def is_ad_present(self):
        """
        检测当前页面是否存在广告元素。
        支持多个广告控件的判断。
        """
        ad_xpaths = [
            "//android.widget.RelativeLayout[@resource-id='com.sina.weibo:id/rl_parent_mini_trans']",
            # "//android.widget.FrameLayout[@resource-id='com.sina.weibo:id/container_tag_root']",
            "//android.widget.FrameLayout[@resource-id='com.sina.weibo:id/svs_module_float_card']",
            # 有遮挡控件类视频，找不到特殊的可屏蔽控件
        ]

        for xpath in ad_xpaths:
            try:
                element = WebDriverWait(self.driver, 2).until(
                    EC.presence_of_element_located((AppiumBy.XPATH, xpath))
                )
                if element and element.is_displayed():
                    logger.info(f"检测到广告、浮窗或遮挡控件")
                    return True
            except Exception as e:
                continue  # 忽略异常，继续检查下一个广告 xpath
        logger.info(f"未检测到广告、浮窗或遮挡控件")
        return False

    def swipe_to_next_video(self):
        width, height = self.get_window_size()
        start_x = width / 2
        start_y = height * 0.8
        end_y = height * 0.2
        self.driver.swipe(start_x, start_y, start_x, end_y, 800)

    def browse_video_page(self):
        if self.is_ad_present():
            print("检测到广告，滑动到下一个视频")
            self.swipe_to_next_video()
        else:
            print("正常视频，继续浏览")

    def base64_to_img(self, base64_string):
        """将 base64 字符串转为 OpenCV 图像"""
        img_data = base64.b64decode(base64_string)
        nparr = np.frombuffer(img_data, np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        return img

    def _find_like_button(self):  # 视频点赞按钮

        max_retries = 3

        # 将模板图片转为 base64
        # 从 base64 转回图片
        template_img = self.base64_to_img(
            'iVBORw0KGgoAAAANSUhEUgAAACQAAAAgCAYAAAB6kdqOAAADmUlEQVRYhc2XS0/6ShiHn+mUYrhoCDtRvIBGlq6MiTG6d+lX8Hucj+J3cemehRoJKCFQCKZcS9vpWZwDwVru/3jOm0woQ2fm6e+99EUAPv8j0/5rgKBtDKTrOltbW0gp/wiQvsniaDRKPp/n+PiYt7c3Xl9fcV13IyAJ/LXu4mw2y/39PdfX1+zt7dFoNGg0GhsBre0yKSXpdJr9/X10XSebzVIoFND1jURfHygWi5HJZEgmkwghiEQiJBIJIpHIRkBrP046nebs7GwSzEIINE1DCPH7QIZhcHR0RD6f/wbgeR5Kqd8FklJyeHjI1dUViURiAuQ4DpZlYdv27wFJKclms9zc3HB6eooQYjJ6vR6maeL7mxX+UKB4PM7u7i6GYeA4DpVKBaUUuVyO29tbLi8vMQwDTdPQtH/ywrZtpJQcHBz8iCMhBEopOp0OlmXNrVUi+C6TUnJxccHd3R3xeBzLsnh8fGQ0GvHw8EA+n0dKOYEZK9TpdKhWq7iuO5kbwwgh8DyPz89Pnp6eeHl5wXGc5RTSNI1CoUAmk0HTNAzDYHt7G9d1OTk5QUr5LaPGY2dnh1Qq9W0uOM7Pz4nFYjSbTer1eijQjzokhJgoML3ZGDbs6WeN8f2apiGlREpJLpcjlUrNdFloDAU3nAYlUHOC4GEw4znXdRkMBnietzpQmELTSgV/X/Td931GoxHVapVut7saUPDAMPWWgZlW2HVdbNumUqlgWdZqQEE1gtez3BSm5vhzNBrx9fVFrVZjOByuBxQ8PAwkTM2wGLRtm2q1SqvVWj2GwmJknosW3eO6Lv1+n3K5TLvdngkzE2jRYcGMWxTUjuPQ6/Wo1Wp0Op31gMavhLHkvu9PQILBPg/c93263S6madJsNhe+fEOBPM/DcZxJqiql8H0f13VRSv3IvFnqeJ6HZVnU63U+Pj5ot9sL25MfQL7vY5ompVIJ3/fp9/v0+308z6NcLn9TJUzZafWUUgwGA3q9HqVSaWH8hAIppWg0GrTbbXzfZzAYMBwOUUphmuZcIAIu5t90f39/p1gszi2Ic4GKxSK6rhONRhkMBjSbTYQQPD8/E4lEZqoTNNd1abVaVCoVTNNcqpv80X6MN08kEui6PuljAJLJ5CSop21WU6aUYjgcYtv20o1bKFAQbnqzMCU27RKnbakWdla8LLt2FeDN/tVNHfqnbKHLVjl4rIRhGMRisUlxJeDWcbEM663/BuNPmDamSR18AAAAAElFTkSuQmCC')
        for attempt in range(max_retries + 1):
            try:
                # 找到模板图片的坐标
                try:
                    xhs_button = WebDriverWait(self.driver, 6).until(
                        EC.element_to_be_clickable(
                            (AppiumBy.XPATH,
                             '//androidx.recyclerview.widget.RecyclerView[@resource-id="com.sina.weibo:id/view_recycler"]/android.widget.FrameLayout/android.view.ViewGroup[4]/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout[3]/android.widget.FrameLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout'))
                    )
                    xhs_button.click()
                    logger.info("成功点击【点赞】")
                    return  # 成功点击后退出循环
                except Exception as e:
                    # logger.warning(f"未找到【点赞】按钮，使用图片识别的方式进行")
                    # x, y = self.find_template_pos(template_img)
                    #
                    # # 点击找到的坐标
                    # self.tap(x, y)
                    # logger.info("成功点击【点赞】")
                    # time.sleep(3)
                    return  # 成功点击后退出循环

            except Exception as e:
                if attempt < max_retries:
                    logger.error(f"点击「点赞」失败，第 {attempt + 1} 次重试... 错误: {e}")
                    time.sleep(1)  # 等待1秒后重试
                else:
                    logger.error(f"点击「点赞」失败，已达到最大重试次数 ({max_retries})，错误: {e}")
                    raise Exception("点击「点赞」失败")

    def tap(self, x, y):
        """点击屏幕指定坐标"""
        self.driver.tap([(x, y)], 500)

    def take_screenshot(self) -> np.ndarray:
        """ADB截屏并转为OpenCV格式"""
        # 通过ADB截屏保存为临时文件
        # subprocess.run("adb exec-out screencap -p > screen.png", shell=True)
        self.driver.save_screenshot('/tmp/screenshot.png')
        # 读取截图
        return cv2.imread("/tmp/screenshot.png")

    def find_template_pos(self, template_img: np.ndarray, threshold: float = 0.5) -> tuple:
        """模板匹配定位坐标"""
        logging.info("开始模板匹配")

        # 截取屏幕并转换为 OpenCV 格式
        screen_img = self.take_screenshot()
        logging.info("截取屏幕成功")

        # 灰度化处理提升性能
        screen_gray = cv2.cvtColor(screen_img, cv2.COLOR_BGR2GRAY)
        template_gray = cv2.cvtColor(template_img, cv2.COLOR_BGR2GRAY)
        logging.info("灰度化处理完成")

        # 使用 TM_CCOEFF_NORMED 算法进行模板匹配
        res = cv2.matchTemplate(screen_gray, template_gray, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

        logging.info(f"模板匹配结果: min_val={min_val}, max_val={max_val}, min_loc={min_loc}, max_loc={max_loc}")

        # 判断匹配结果是否满足阈值要求
        if max_val < threshold:
            logging.warning(f"模板匹配失败，最大值 {max_val} 低于阈值 {threshold}")
            raise ValueError("未找到匹配图片")
        else:
            logging.info(f"模板匹配成功，最大值 {max_val} 高于阈值 {threshold}")

        # 计算中心点坐标（适配模板尺寸）
        h, w = template_gray.shape
        center_x = max_loc[0] + w // 2
        center_y = max_loc[1] + h // 2

        logging.info(f"计算得到中心点坐标: ({center_x}, {center_y})")

        return center_x, center_y

    def find_elements_with_retry(self, by, value, timeout=5):
        max_retries = 3
        for attempt in range(max_retries + 1):
            try:
                elements = WebDriverWait(self.driver, timeout).until(
                    EC.presence_of_all_elements_located((by, value))
                )
                return elements
            except Exception as e:
                if attempt < max_retries:
                    logger.error(f"获取元素列表失败，重试")
                    time.sleep(1)  # 等待1秒后重试
                else:
                    logger.error(f"获取元素列表失败，超过3次")
                    logger.error(f"元素名称: {value}")
                    return []

    def try_click_card(self):
        # 查找所有视频卡片元素
        video_cards = self.find_elements_with_retry(
            AppiumBy.XPATH,
            value='//android.widget.FrameLayout[@resource-id="com.sina.weibo:id/video_feed_video_player_view"]'
        )

        clicked = False
        if video_cards:
            # 随机选择一个视频卡片点击
            selected_video = random.choice(video_cards)
            try:
                selected_video.click()
                logger.info("点击进入视频卡片")
                self.handle_video_page()
                time.sleep(3)
                # 返回推荐页
                self.driver.press_keycode(4)
                logger.info("返回第1次")
                time.sleep(2)
                clicked = True
            except Exception as e:
                logger.error(f"点击视频卡片失败: {e}")

        # 如果没有点击视频卡片或点击失败，则尝试点击图文卡片
        if not clicked:
            # 查找所有图文卡片元素
            picture_cards = self.find_elements_with_retry(
                AppiumBy.XPATH,
                value='//android.widget.FrameLayout[@resource-id="com.sina.weibo:id/weibo_image"]'
            )

            if picture_cards:
                # 随机选择一个图文卡片点击
                selected_picture = random.choice(picture_cards)
                try:
                    selected_picture.click()
                    logger.info("点击进入图文卡片")
                    self.handle_note_page()
                    time.sleep(3)
                    # 返回推荐页
                    self.driver.press_keycode(4)
                    logger.info("返回第1次")
                    time.sleep(2)
                except Exception as e:
                    logger.error(f"点击图文卡片失败: {e}")

    def handle_note_page(self):
        logger.info("执行图文笔记页操作")
        if not self.is_note_detail_page():
            logger.warning("当前页面不是图文详情页，跳过点赞操作")
            return

        if random.random() < 0.9:
            self.swipe_to_next()
            time.sleep(random.uniform(1.5, 3))

        # 点赞
        if random.random() < self.like_prob:
            try:
                like_button = self.find_element_with_retry(
                    by=AppiumBy.XPATH,
                    value='//android.widget.FrameLayout[starts-with(@content-desc, "点赞")]',
                    # by=AppiumBy.ANDROID_UIAUTOMATOR,
                    # value='new UiSelector().resourceId("com.sina.weibo:id/btn_like")',
                    timeout=10
                )
                like_button.click()
                time.sleep(random.uniform(1.5, 3))
                logger.info("图文笔记点赞成功")
            except Exception as e:
                logger.warning(f"图文笔记点赞失败: {e}")
            # 滑动完成后，返回推荐页

    def handle_video_page(self):
        logger.info("执行视频动态页操作")
        # 随机滑动 2~10 次
        swipe_times = random.randint(5, 10)
        logger.info(f"开始向下滑动 {swipe_times} 次，查看更多内容")
        time.sleep(random.uniform(2, 5))
        for i in range(swipe_times):
            self.swipe_to_next()
            logger.info(f"第 {i + 1} 次滑动完成")

            logger.info("开始检测是否存在广告元素")
            self.browse_video_page()  # 广告检测 + 滑动跳过
            time.sleep(random.uniform(1.5, 3))

            if self.is_ad_present():
                logger.info("检测到广告内容，跳过点赞操作")
                continue  # 不执行后续点赞逻辑
            # 点赞
            if random.random() < self.like_prob:
                # 点击点赞按钮（使用元素定位及图像对比方式）
                self._find_like_button()

            time.sleep(random.uniform(4, 5))

    def swipe_to_next(self):
        # 向上滑动
        try:
            self.driver.swipe(
                self.screen_width / 2.5,
                self.screen_height * 0.8,
                self.screen_width / 2.5,
                self.screen_height * 0.2,
                200
            )
        except Exception as e:
            logger.error(f"滑动失败: {e}")

    def find_element_with_retry(self, by, value, timeout=5):
        max_retries = 3
        for attempt in range(max_retries + 1):
            try:
                element = WebDriverWait(self.driver, timeout).until(
                    EC.presence_of_element_located((by, value))
                )
                return element
            except Exception as e:
                if attempt < max_retries:
                    logger.error(f"获取元素失败，重试")
                    time.sleep(1)  # 等待1秒后重试
                else:
                    logger.error(f"获取元素失败，超过3次")
                    logger.error(f"元素名称: {value}")
                    return None

    def get_window_size(self):
        size = self.driver.get_window_size()
        return size['width'], size['height']

    def normal_end(self):
        logger.info("返回首页并退出")
        self.driver.press_keycode(3)  # HOME 键
        self.driver.quit()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-accountId', '--accountId', dest='accountId', type=str, default="000", help='target accountId')
    parser.add_argument('-j', '--job_id', dest='job_id', type=str, default=None, help='target job_id')
    parser.add_argument('-u', '--appium_url', dest='appium_url', type=str, default=None, help='target appium_url')
    parser.add_argument('-d', '--deviceName', dest='deviceName', type=str, default=None, help='target deviceName')
    parser.add_argument('-s', '--systemPort', dest='systemPort', type=str, default=None, help='target systemPort')
    parser.add_argument('-a', '--adbPort', dest='adbPort', type=str, default=None, help='target adbPort')
    parser.add_argument('-p', '--platformName', dest='platformName', type=str, default=None, help='target platformName')
    parser.add_argument('-ver', '--platformVersion', dest='platformVersion', type=str, default=None,
                        help='target platformVersion')
    parser.add_argument('-v', '--variables', dest='variables', type=str, default='{}', help='target variables')
    parser.add_argument('-seconds', '--seconds', dest='seconds', type=int, default=600, help='seconds')
    parser.add_argument('-like_prob', '--like_prob', type=float, default=90)
    # parser.add_argument('-collect_prob', '--collect_prob', type=float, default=0.1)
    parser.add_argument('-follow_prob', '--follow_prob', type=float, default=0.05)
    parser.add_argument('-searchProb', '--searchProb', type=float, default=80)
    parser.add_argument('-keyWord', '--keyWord', type=str, default="美食\n旅行\n健身")
    # parser.add_argument('--follow_prob', type=float, default=0.05)

    args = parser.parse_args()
    WBAppiumOperate(**vars(args)).run()
